<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<!-- <view class="custom-nav">
			<view class="nav-content">
				<view class="back" @click="handleBack">
					<text class="iconfont icon-back"></text>
				</view>
				<text class="title">编辑资料</text>
			</view>
		</view> -->
		
		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 头像上传区域 -->
			<view class="avatar-section">
				<image :src="avatarUrl" 
					   class="avatar" 
					   @click="chooseImage" />
				<text class="tip">点击更换头像</text>
			</view>
			
			<view class="form-group">
				<text class="label">用户名</text>
				<input type="text" 
					   v-model="form.username" 
					   placeholder="请输入用户名"
					   class="input" />
			</view>
			
			<view class="form-group">
				<text class="label">密码</text>
				<input type="password" 
					   v-model="form.password" 
					   placeholder="不修改请留空"
					   class="input" />
			</view>
			
			<!-- 联系方式按钮 -->
			<view class="contact-btn" @click="showContactModal">
				<text class="iconfont icon-contact"></text>
				<text class="btn-text">编辑联系方式</text>
			</view>
			
			<!-- 保存按钮 -->
			<button class="save-btn" 
					:disabled="!isFormValid"
					@click="handleSave">
				保存修改
			</button>
		</view>
		
		<!-- 联系方式弹窗 -->
		<uni-popup ref="contactPopup" type="center">
			<view class="contact-modal">
				<view class="modal-header">
					<text class="title">编辑联系方式</text>
					<text class="iconfont icon-close" @click="hideContactModal"></text>
					<text class="subtitle">请填写真实信息，虚假信息将导致奖励取消</text>
				</view>
				<scroll-view scroll-y 
							class="modal-body" 
							:style="{ maxHeight: modalMaxHeight + 'px' }">
					<!-- 社交媒体分组 -->

					<view class="form-section">
						<text class="section-title">社交账号</text>
						<view class="social-grid">
							<view class="social-item" :class="{ active: activeInput === 'wechat' }">
								<text class="iconfont icon-wechat"></text>
								<input type="text" 
									   v-model="contactForm.wechat" 
									   placeholder="微信" 
									   @focus="activeInput = 'wechat'"
									   @blur="activeInput = ''" />
							</view>
							<view class="social-item" :class="{ active: activeInput === 'qq' }">
								<text class="iconfont icon-qqqingliao"></text>
								<input type="number" 
									   v-model="contactForm.qq" 
									   placeholder="QQ" 
									   @focus="activeInput = 'qq'"
									   @blur="activeInput = ''" />
							</view>
							<view class="social-item" :class="{ active: activeInput === 'weibo' }">
								<text class="iconfont icon-weibo"></text>
								<input type="text" 
									   v-model="contactForm.weibo" 
									   placeholder="微博" 
									   @focus="activeInput = 'weibo'"
									   @blur="activeInput = ''" />
							</view>
							<view class="social-item" :class="{ active: activeInput === 'douyin' }">
								<text class="iconfont icon-douyin"></text>
								<input type="text" 
									   v-model="contactForm.douyin" 
									   placeholder="抖音" 
									   @focus="activeInput = 'douyin'"
									   @blur="activeInput = ''" />
							</view>
						</view>
					</view>

					<!-- 基本联系方式分组 -->
					<view class="form-section">
						<text class="section-title">基本联系方式</text>
						<view class="contact-list">
							<view class="contact-item" :class="{ active: activeInput === 'phone' }">
								<text class="iconfont icon-phone"></text>
								<input type="number" 
									   v-model="contactForm.phone" 
									   placeholder="手机号码"
									   @focus="activeInput = 'phone'"
									   @blur="activeInput = ''" />
							</view>
							<view class="contact-item" :class="{ active: activeInput === 'email' }">
								<text class="iconfont icon-email"></text>
								<input type="text" 
									   v-model="contactForm.email" 
									   placeholder="电子邮箱"
									   @focus="activeInput = 'email'"
									   @blur="activeInput = ''" />
							</view>
							<view class="contact-item" :class="{ active: activeInput === 'address' }">
								<text class="iconfont icon-address"></text>
								<input type="text" 
									   v-model="contactForm.address" 
									   placeholder="联系地址或收货地址"
									   @focus="activeInput = 'address'"
									   @blur="activeInput = ''" />
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="modal-footer">
					<button class="btn cancel" @click="hideContactModal">取消</button>
					<button class="btn confirm" @click="saveContact">保存</button>
				</view>
			</view>
		</uni-popup>
		
		<!-- 添加注销按钮 -->
		<view class="delete-account-section">
			<button class="delete-btn" @click="showDeleteConfirm">注销账号</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { api } from '@/utils/request'

// 表单数据
const form = ref({
	username: '',
	password: '',
	user_id: ''
})

// 计算弹窗内容区域最大高度
const modalMaxHeight = ref(0)

// 初始化弹窗高度
const initModalHeight = () => {
	const systemInfo = uni.getSystemInfoSync()
	// 设置为屏幕高度的60%，同时考虑头部和底部的高度
	modalMaxHeight.value = systemInfo.windowHeight * 0.6
}

// 头像相关
const avatarUrl = ref('/static/delault/user_at.png')
const tempFilePath = ref('')

// 表单验证
const isFormValid = computed(() => {
	return form.value.username.trim() !== ''
})

// 返回上一页
const handleBack = () => {
	uni.navigateBack()
}

// 初始化表单数据
const initForm = () => {
	const userInfo = uni.getStorageSync('userInfo')
	if (userInfo) {
		form.value.username = userInfo.username
		form.value.user_id = userInfo.user_id
		// 设置当前头像
		if (userInfo.avatar) {
			avatarUrl.value = api.BASE_URL + userInfo.avatar
		}
	}
}

// 选择图片
const chooseImage = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			tempFilePath.value = res.tempFilePaths[0]
			avatarUrl.value = tempFilePath.value
		}
	})
}

// 保存修改
const handleSave = async () => {
	if (!isFormValid.value) {
		uni.showToast({
			title: '请填写用户名',
			icon: 'none'
		})
		return
	}
	
	try {
		// 如果没有选择新头像，使用普通的 request
		if (!tempFilePath.value) {
			const res = await api.request({
				url: '/api/user/edit/',
				method: 'POST',
				data: {
					username: form.value.username,
					password: form.value.password || '',
					user_id: form.value.user_id
				}
			})
			return handleResponse(res)
		}

		// 有新头像时使用 uploadFile
		const res = await new Promise((resolve, reject) => {
			uni.uploadFile({
				url: api.BASE_URL + '/api/user/edit/',
				filePath: tempFilePath.value,
				name: 'avatar',
				formData: {
					username: form.value.username,
					password: form.value.password || '',
					user_id: form.value.user_id
				},
				success: (uploadRes) => {
					if (typeof uploadRes.data === 'string') {
						uploadRes.data = JSON.parse(uploadRes.data)
					}
					resolve(uploadRes.data)
				},
				fail: reject
			})
		})
		
		handleResponse(res)
	} catch (e) {
		console.error(e)
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		})
	}
}

// 处理响应
const handleResponse = (res) => {
	if (res.code === 200) {
		// 更新本地存储的用户信息
		const userInfo = uni.getStorageSync('userInfo')
		userInfo.username = res.data.username
		userInfo.avatar = res.data.avatar
		uni.setStorageSync('userInfo', userInfo)
		
		uni.showToast({
			title: '保存成功',
			icon: 'success'
		})
		
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	} else {
		uni.showToast({
			title: res.message || '保存失败',
			icon: 'none'
		})
	}
}

// 联系方式表单
const contactForm = ref({
	user_id: '',
	phone: '',
	email: '',
	address: '',
	wechat: '',
	weibo: '',
	qq: '',
	douyin: '',
	kuaishou: '',
	xiaohongshu: '',
	zhihu: '',
	other: ''
})

const contactPopup = ref(null)

// 从本地存储获取联系方式
const getLocalContact = () => {
	const contactInfo = uni.getStorageSync('contactInfo')
	if (contactInfo) {
		Object.keys(contactForm.value).forEach(key => {
			if (contactInfo[key] !== null) {
				contactForm.value[key] = contactInfo[key]
			}
		})
		return true
	}
	return false
}

// 保存联系方式到本地
const saveLocalContact = (data) => {
	uni.setStorageSync('contactInfo', data)
}

// 获取联系方式
const getContactInfo = async () => {
	try {
		const res = await api.request({
			url: '/api/contact/get/',
			method: 'GET',
			data: {
				user_id: form.value.user_id
			}
		})
		
		if (res.code === 200 && res.data) {
			// 更新表单数据
			Object.keys(contactForm.value).forEach(key => {
				if (res.data[key] !== null) {
					contactForm.value[key] = res.data[key]
				}
			})
			// 保存到本地存储
			saveLocalContact(res.data)
		} else {
			uni.showToast({
				title: res.message || '获取联系方式失败',
				icon: 'none'
			})
		}
	} catch (e) {
		console.error('获取联系方式失败:', e)
		uni.showToast({
			title: '获取联系方式失败',
			icon: 'none'
		})
	}
}

// 显示联系方式弹窗
const showContactModal = () => {
	// 先尝试从本地获取
	const hasLocalData = getLocalContact()
	
	// 如果本地没有数据，则从服务器获取
	if (!hasLocalData) {
		getContactInfo()
	}
	
	contactPopup.value.open()
}

// 隐藏联系方式弹窗
const hideContactModal = () => {
	contactPopup.value.close()
}

// 保存联系方式
const saveContact = async () => {
	try {
		const res = await api.request({
			url: '/api/contact/create/',
			method: 'POST',
			data: {
				...contactForm.value,
				user_id: form.value.user_id
			}
		})
		
		if (res.code === 200) {
			// 保存成功后更新本地存储
			saveLocalContact(contactForm.value)
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})
			hideContactModal()
		} else {
			uni.showToast({
				title: res.message || '保存失败',
				icon: 'none'
			})
		}
	} catch (e) {
		console.error(e)
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		})
	}
}

// 当前激活的输入框
const activeInput = ref('')

// 显示注销确认对话框
const showDeleteConfirm = () => {
	uni.showModal({
		title: '确认注销',
		content: '注销后账号将无法恢复，确定要注销吗？',
		confirmColor: '#ff0000',
		success: (res) => {
			if (res.confirm) {
				deleteAccount()
			}
		}
	})
}

// 注销账号
const deleteAccount = async () => {
	try {
		const userId = uni.getStorageSync('user_id')
		const res = await api.request({
			url: '/api/user/delete/',
			method: 'GET',
			params: {
				user_id: userId
			}
		})
		
		if (res.code === 200) {
			// 清空所有本地存储
			uni.clearStorageSync()
			
			// 显示成功提示
			uni.showToast({
				title: '注销成功',
				icon: 'success'
			})
			
			// 延迟跳转到登录页
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}, 100)
		} else {
			uni.showToast({
				title: res.message || '注销失败',
				icon: 'error'
			})
		}
	} catch (error) {
		console.error('注销失败:', error)
		uni.showToast({
			title: '注销失败，请稍后重试',
			icon: 'error'
		})
	}
}

onMounted(() => {
	initForm()
	initModalHeight()
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
	
	.custom-nav {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff;
		padding-top: var(--status-bar-height);
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		
		.nav-content {
			position: relative;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.back {
				position: absolute;
				left: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				padding: 10rpx;
				
				.iconfont {
					font-size: 40rpx;
					color: #333;
				}
			}
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
	
	.form-container {
		padding: calc(var(--status-bar-height) + 88rpx + 20rpx) 30rpx 30rpx;
		
		.avatar-section {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0;
			
			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 80rpx;
				background-color: #f5f5f5;
				margin-bottom: 20rpx;
			}
			
			.tip {
				font-size: 24rpx;
				color: #999;
			}
		}
		
		.form-group {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			
			.label {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 10rpx;
				display: block;
			}
			
			.input {
				width: 100%;
				height: 80rpx;
				font-size: 30rpx;
				color: #333;
			}
		}
		
		.save-btn {
			margin-top: 60rpx;
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			background: #007AFF;
			color: #fff;
			font-size: 32rpx;
			border-radius: 44rpx;
			
			&:disabled {
				opacity: 0.5;
			}
		}
	}
}

.contact-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 30rpx;
	padding: 20rpx;
	background: #f5f5f5;
	border-radius: 12rpx;
	
	.iconfont {
		font-size: 40rpx;
		color: #007AFF;
		margin-right: 10rpx;
	}
	
	.btn-text {
		font-size: 28rpx;
		color: #007AFF;
	}
	
	&:active {
		opacity: 0.7;
	}
}

.contact-modal {
	width: 680rpx;
	background: #fff;
	border-radius: 30rpx;
	overflow: hidden;
	max-height: 90vh; // 限制最大高度
	
	.modal-header {
		position: relative;
		padding: 40rpx 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #f0f0f0;
		background: linear-gradient(to right, #f8f9fa, #e9ecef);
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			text-shadow: 1px 1px 0 rgba(255,255,255,0.8);
		}
		
		.subtitle {
			display: block;
			font-size: 24rpx;
			color: #ff4d4f;
			margin-top: 10rpx;
			
			&::before {
				content: '!';
				display: inline-block;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				background: #ff4d4f;
				color: #fff;
				border-radius: 50%;
				margin-right: 8rpx;
				font-size: 20rpx;
				font-weight: bold;
			}
		}
		
		.icon-close {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 40rpx;
			color: #999;
			padding: 20rpx;
		}
	}
	
	.modal-body {
		height: 100%;
		padding: 30rpx;
		box-sizing: border-box;
		-webkit-overflow-scrolling: touch; // 增加弹性滚动
		
		.form-section {
			margin-bottom: 40rpx;
			
			.section-title {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
				display: block;
				position: relative;
				padding-left: 20rpx;
				
				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 6rpx;
					height: 24rpx;
					background: #007AFF;
					border-radius: 3rpx;
				}
			}
			
			.social-grid {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 20rpx;
				
				.social-item {
					min-height: 88rpx;
					background: #f8f9fa;
					border-radius: 16rpx;
					padding: 20rpx;
					display: flex;
					align-items: center;
					transition: all 0.3s ease;
					border: 2rpx solid transparent;
					box-sizing: border-box;
					
					.iconfont {
						font-size: 40rpx;
						margin-right: 20rpx;
						flex-shrink: 0;
						
						&.icon-wechat { color: #07c160; }
						&.icon-QQ { color: #12b7f5; }
						&.icon-weibo { color: #ff8200; }
						&.icon-douyin { color: #000000; }
					}
					
					input {
						flex: 1;
						font-size: 28rpx;
						color: #333;
						background: transparent;
						min-width: 0;
					}
					
					&.active {
						background: #fff;
						border-color: #007AFF;
						box-shadow: 0 4rpx 12rpx rgba(0,122,255,0.1);
					}
				}
			}
			
			.contact-list {
				.contact-item {
					min-height: 88rpx;
					background: #f8f9fa;
					border-radius: 16rpx;
					padding: 24rpx;
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					transition: all 0.3s ease;
					border: 2rpx solid transparent;
					box-sizing: border-box;
					
					.iconfont {
						font-size: 36rpx;
						color: #007AFF;
						margin-right: 20rpx;
						flex-shrink: 0;
					}
					
					input {
						flex: 1;
						font-size: 28rpx;
						color: #333;
						background: transparent;
						min-width: 0;
					}
					
					&.active {
						background: #fff;
						border-color: #007AFF;
						box-shadow: 0 4rpx 12rpx rgba(0,122,255,0.1);
					}
				}
			}
		}
	}
	
	.modal-footer {
		display: flex;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		background: #f8f9fa;
		
		.btn {
			flex: 1;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 32rpx;
			border-radius: 44rpx;
			margin: 0 15rpx;
			transition: all 0.3s ease;
			
			&.cancel {
				background: #f1f3f5;
				color: #666;
				
				&:active {
					background: #e9ecef;
				}
			}
			
			&.confirm {
				background: linear-gradient(135deg, #007AFF, #0056b3);
				color: #fff;
				
				&:active {
					transform: scale(0.98);
				}
			}
		}
	}
}

/* 注销按钮样式 */
.delete-account-section {
	margin-top: 50rpx;
	padding: 0 30rpx;
}

.delete-btn {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	background-color: #fff;
	color: #ff0000;
	border: 1px solid #ff0000;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.delete-btn:active {
	background-color: #fff5f5;
}
</style>